from sklearn.model_selection import GridSearchCV
from sklearn.metrics import make_scorer, recall_score, confusion_matrix

class ModelOptimizer:
    def __init__(self, model, param_grid):
        self.model = model
        self.param_grid = param_grid
        
    def optimize_for_security(self, X, y):
        """针对安全场景优化（降低误报和漏报）"""
        custom_scorer = make_scorer(
            lambda y_true, y_pred: 0.5 * recall_score(y_true, y_pred) + 0.5 * (1 - self._calculate_fpr(y_pred)),
            greater_is_better=True
        )
        
        grid_search = GridSearchCV(
            estimator=self.model,
            param_grid=self.param_grid,
            scoring=custom_scorer,
            cv=5,
            n_jobs=-1
        )
        grid_search.fit(X, y)
        return grid_search.best_estimator_
    
    def _calculate_fpr(self, y_pred, y_true):
        tn, fp, _, _ = confusion_matrix(y_true, y_pred).ravel()
        return fp / (fp + tn) 

# 在模型参数中调整类别权重
param_grid = {
    'class_weight': [{0:1, 1:3}, {0:1, 1:5}],  # 提高恶意样本权重
    'max_depth': [10, 20]
} 